package com.Long.mqAck;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

/**
 * @Title:
 * @Description:
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/7/26
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
public class ConfirmProducer {
    public static final String FANOUT_EXCHANAGE_ACK = "FANOUT_EXCHANAGE_ACK";
    public static final String USER_NAME = "admin";
    public static final String PASSWORD = "admin";
    public static final String HOST = "47.101.154.152";
    public static final int PORT = 5672;
    public static final String QUEUW_NAME1 = "queue3";
    public static final String ROUTING_KEY = "ack.queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST);
        factory.setPort(PORT);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();//创建信道；
        //指定消息的投递模式：confirm模式
        channel.confirmSelect();

        final long start = System.currentTimeMillis();
        channel.exchangeDeclare(FANOUT_EXCHANAGE_ACK, "direct", true, false, null);
        //创建队列
        channel.queueDeclare(QUEUW_NAME1, true, false, false, null);
        //将交换器与队列通过路由键进行绑定
        channel.queueBind(QUEUW_NAME1, FANOUT_EXCHANAGE_ACK, ROUTING_KEY);

        for (int i = 0; i < 10; i++) {
            String msf = "this is confirm msg";


            channel.basicPublish(FANOUT_EXCHANAGE_ACK, ROUTING_KEY,null, msf.getBytes());

            System.out.println("send msg success" + i);
        }
        channel.addConfirmListener(new ConfirmListener() {
            /*
             * 返回成功的回调函数
             * */
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("success ack!");
                System.out.println(multiple);
                System.out.println("耗时：" + (System.currentTimeMillis() - start) + "ms");
            }

            /*
             * 返回失败的回调函数
             *
             * */
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.printf("defeat ack  multiple:"+multiple);
                System.out.println("耗时：" + (System.currentTimeMillis() - start) + "ms");
            }
        });


    }
}
